package nl.haemers.base
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.Dictionary;
	
	import nl.haemers.utils.Destroyer;
	import nl.haemers.base.IDestructible;
	
	/**
	 * @author Jonathan Haemers
	 * 
	 * All the credits for the eventListenerDictionary goes to Mark Knol 
	 * http://blog.stroep.nl/2010/09/remove-eventlisteners-in-as3/
	 * Thanks Mark :)
	 */
	public class BaseSprite extends Sprite implements IDestructible
	{
		private var eventListenerDictionary				:Dictionary;
		private var eventObject							:EventListenerObject;
		
		public function BaseSprite() 
		{
			eventListenerDictionary = new Dictionary();
			if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		/** Public methods **/
		override public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false) : void
		{
			super.addEventListener(type, listener, useCapture, priority, useWeakReference);
			
			eventListenerDictionary[type] = new EventListenerObject(type, listener, useCapture);
		}
		
		override public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false) : void
		{
			eventObject = eventListenerDictionary[type];
				
			super.removeEventListener(eventObject.type, eventObject.listener, eventObject.useCapture);
			delete eventListenerDictionary[type];
			
			eventObject = null;
		}
		
		public function removeAllEventListeners() : void
		{
			for (var eventType:String in eventListenerDictionary) 
			{
				eventObject = eventListenerDictionary[eventType];
				super.removeEventListener(eventObject.type, eventObject.listener, eventObject.useCapture);
				
				eventObject = null;
			}
		}
		
		public function destroy() : void
		{
			removeAllEventListeners();
			//misschien nog aan passen dat hij in deze class komt. & dat hij zichzelf van de stage af gooit.
			Destroyer.destroy(this);
		}
		
		/** Getters & Setters **/
		
		/** Protected methods **/
		protected function init( e:Event = null ) : void
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		/** Private methods **/
		
	}
	
	
	
}

internal class EventListenerObject
{
	public var type					:String;
	public var listener				:Function;
	public var useCapture			:Boolean;
	
	public function EventListenerObject(type:String, listener:Function, useCapture:Boolean = false) : void
	{
		this.type = type;
		this.listener = listener;
		this.useCapture = useCapture;
	}
}